const express = require('express');
const router = express.Router();
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
const upload = require('../multer/multer')
const { generateToken, parseToken } = require('../utils/token')
const { returnWorkArticleData } = require('../utils/prismaData');
const { transToSql, transToText, insertImgUrl } = require('../utils/transChar');
const { generateArticleId } = require('../utils/uuid')
const baseURL = process.env.BASE_URL


// 发送已加入的专栏和已有的标签
router.get('/tag', upload.none(), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id, user } = tokenData

    const articleId = req.query.articleId
    if (articleId === '') {
        await prisma.$transaction([
            prisma.tag.findMany(),
            prisma.column.findMany({
                select: {
                    id: true,
                    name: true,
                    mainPath: true,
                    createId: true,
                }
            })
        ]).then((result) => {
            // 包装数据
            const tags = result[0].map(tag => {
                return tag.name
            })
            const columns = result[1].map(column => {
                return { columnId: column.id, columnName: column.name }
            })
            const data = { tags: tags, columns: columns }
            return res.status(200).send(data)
        }).catch((err) => {
            return res.status(404).send({ msg: '无相关内容' })
        }).finally(async () => {
            await prisma.$disconnect();
        })
    } else {
        await prisma.$transaction([
            prisma.tag.findMany({
                where: {
                    article: articleId
                }
            }),
            prisma.column.findMany({
                where: {
                    article: articleId
                },
                select: {
                    id: true,
                    name: true,
                    mainPath: true,
                    createId: true,
                }
            })
        ]).then((result) => {
            return res.status(200).send({ tags: result[0], columns: result[1] })
        }).catch((err) => {
            return res.status(404).send({ msg: '无相关内容' })
        }).finally(async () => {
            await prisma.$disconnect();
        })
    }

})

// 获取文章或续写文章
router.get('/text', async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id, user } = tokenData
    const articleId = req.query.articleId
    // 从数据库读取指定文章id的数据
    const workArticleData = await prisma.article.findUnique({
        where: {
            id: articleId
        }
    })
    if (workArticleData === null) return res.status(404).send({ msg: '未知文章索引' })
    // 数据处理
    if (workArticleData.authorId !== id) return res.status(403).send({ msg: '用户权限错误' })

    // 更新记录检查
    const data = returnWorkArticleData(workArticleData)
    // 
    res.status(200).send(data)

})


// 发布
router.post('/publish', upload.any(), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    // 可能还会有主图
    const { articleId, columnId, tags, title, userId, public, ...contentText } = req.body
    // 处理文本
    const textInfoArray = transToSql(contentText)

    // 主图 path
    let filePath = undefined
    const mainImgFile = req.files.filter(file => file.fieldname === 'mainImg')
    if (mainImgFile.length !== 0) {
        filePath = mainImgFile[0].path.replace('public\\', '')
    }
    // 处理图片
    const fileArray = req.files.map(file => ({ name: file.fieldname, path: file.path.replace('public/', '') }))
    const fileInfoArray = fileArray.filter(file => file.name !== 'mainImg')
    // http 图片数据
    const httpFile = textInfoArray.filter(item => item.name.startsWith('contentImg'))
    const httpInfo = httpFile.map(file => ({ name: file.name, path: file.content.replace(baseURL + '/', '').replace(/\//, '\\') }))
    // 要写入的文章内容
    const text = insertImgUrl(textInfoArray.concat(fileInfoArray, httpInfo))
    const views = public === '1' ? true : false

    // 文章的标签
    const tagsName = tags.split('&')
    if (tagsName.length >= 8) return res.status(403).send({ msg: '标签过多' })
    // 文章所属的专栏
    console.log(articleId);
    if (articleId === '') {
        console.log('创建');
        // 生成唯一标识并保存
        const articleId = generateArticleId()
        // 保存
        const articleData = {
            id: articleId,
            published: views,
            mainImg: filePath,
            title: title,
            content: text,
            authorId: userId,
            tags: {
                connectOrCreate: tagsName.map(tag => ({
                    where: { name: tag },
                    create: { name: tag }
                }))
            }
        };
        
        // 根据需要决定是否添加columns
        if (columnId) {
            articleData.columns = {
                connectOrCreate: {
                    where: { columnId: columnId, articleId: articleId },
                    create: { columnId: columnId }
                }
            };
        }
        await prisma.$transaction([
            prisma.article.create({
                data: articleData
            })
        ])
            .then((result) => {
                return res.status(200).send({ msg: '保存成功', articleId })
            })
            .catch((err) => {
                return res.status(403).send({ msg: '保存失败' })
            })
            .finally(async () => {
                await prisma.$disconnect();
            })
    } else {
        console.log('续写');
        // 查询唯一标识
        const articleData = await prisma.article.findUnique({
            where: {
                id: articleId
            }
        })
        if (articleData === null) return res.status(403).send({ msg: '未找到文章' })
        // 保存
        try {
            const articleUpdata = await prisma.article.update({
                where: {
                    id: articleId
                },
                data: {
                    published: views,
                    mainImg: filePath,
                    title: title,
                    content: text,
                    authorId: userId,
                }
            })
            if (articleUpdata === null) return res.status(403).send({ msg: '保存失败' })
            res.status(200).send({ msg: '保存成功', articleId })
        } catch (error) {
            res.status(500).send({ msg: '数据库执行错误' })
        }
    }
})




// 文件解析
router.post('/', () => {

})

module.exports = router